package com.hc.handler;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理全局异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕捉shiro的异常
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result handler(ShiroException e) {
        log.error("ShiroException：", e);
        String msg = e.getMessage();
        log.info(msg);
        if (msg.contains("role")) {
            return ResultUtil.fail(99401, "当前用户不具备访问该资源的角色");
        } else if (msg.contains("permission")) {
            return ResultUtil.fail(99401, "当前用户不具备访问该资源的权限");
        }
        return ResultUtil.fail(99401, e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handler(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException：", e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultUtil.fail(99403, objectError.getDefaultMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        log.error("IllegalArgumentException：", e);
        return ResultUtil.fail(99404, e.getMessage());
    }

    /**
     * 捕捉其他所有异常
     *
     * @param request
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(RuntimeException.class)
    public Result globalException(HttpServletRequest request, RuntimeException e) {
        log.error("运行时异常：", e);
        HttpStatus httpStatus;
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        httpStatus = HttpStatus.valueOf(statusCode);
        return ResultUtil.fail(httpStatus.value(), e.getMessage());
    }
}
